<?php

namespace App\Modules\EnterpriseWechat\Packages\EnterpriseWeChat\src;

use App\Exceptions\ApiException;
use http\Encoding\Stream\Inflate;

/**
 * 目前是单应用多模版，如果有多应用需要配置多回调地址
 */
class EnterpriseWechat
{
    /**
     * @param $corpId
     * @param $secret
     * @return void
     * 获取access_token
     */
    public static function getToken($corpId, $secret)
    {
        //获取token
        $accessTokenUrl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . $corpId . '&corpsecret=' . $secret;
        $result = file_get_contents($accessTokenUrl);
        $accessToken = json_decode($result)->access_token;
        return $accessToken;
    }


    /**
     * @param $data
     * @return void
     * 添加模板，并且获取模版详情
     */
    public static function addTemplate($data)
    {
        $corpId = config('enterprise_wechat.corpId'); //企业id
        $secret = config('enterprise_wechat.secret'); //回调里面的token
        $encodingAesKey = config('enterprise_wechat.encodingAesKey'); //回调里面的EncodingAESKey
        $token = config('enterprise_wechat.token'); //回调里面的token

        //同样的配置不能存在多条
        $accessToken = self::getToken($corpId, $secret);
        //获取审批模版详情
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/oa/gettemplatedetail?access_token=' . $accessToken;
        $send_data = array(
            'template_id' => $data['template_id']
        );
        $options = array(
            'http' => array(
                'header' => "Content-type: application/json",
                'method' => 'POST',
                'content' => json_encode($send_data),
            )
        );

        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        //有数据再进行模版添加，否则直接报错
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            throw new ApiException('获取审批模版详情失败');
        }
        $controls = $result['template_content']['controls'];
        //目前只允许存在一个多行文本
        if (count($controls) != 1) {
            throw new ApiException('模版配置错误');
        }
        $contents_id = $controls[0]['property']['id'];


        return [
            'corp_id' => $corpId,
            'template_id' => $data['template_id'],
            'secret' => $secret,
            'encoding_aes_key' => $encodingAesKey,
            'token' => $token,
            'contents_id' => $contents_id,
        ];


    }

    /**
     * @param $data
     * @return void
     * 发送企微审批
     */
    public static function send($data, $config)
    {
        $corpId = $config->corp_id;
        $secret = $config->secret;
        $template_id = $config->template_id;

        $accessToken = self::getToken($corpId, $secret);

        //审批
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/oa/applyevent?access_token=' . $accessToken;

        $send_data = array(
            'creator_userid' => 'wujianxiong',//发起人的微信user_id,后面可能需要跟后台账号做绑定，申请人需在应用可见范围内
            'template_id' => $template_id,
            'use_template_approver' => 1,//使用此模板在管理后台设置的审批流程
            //申请流的参数后续考虑存表或者去详情获取后进行截取
            'apply_data' => [
                'contents' => [
                    [
                        "control" => "Textarea",
                        "id" => $config->contents_id,//通过模版详情获取到的id
                        "value" => [
                            "text" => $data['content'],
                            "lang" => "zh_CN"
                        ]
                    ]
                ]
            ],
            "summary_list" => [
                [
                    "summary_info" => [
                        [
                            "text" => self::truncate_string($data['content'], 10),//后面截取....
                            "lang" => "zh_CN"
                        ]
                    ]
                ]
            ]
        );


        $options = array(
            'http' => array(
                'header' => "Content-type: application/json",
                'method' => 'POST',
                'content' => json_encode($send_data),
            )
        );

        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        //微信审批表，记录对应的审批号和模版id
        \Log::error($result);
        $result = json_decode($result, true);
        $code = $result['errcode'];
        if ($code != 0) {
            throw new ApiException('发起企微审批流失败');
        }
        return $result;


    }

    # 定义一个函数，用于截断字符串
    public static function truncate_string($string, $length, $ellipsis = '...')
    {
        # 如果字符串长度大于指定长度，则截断字符串
        if (mb_strlen($string, 'UTF-8') > $length) {
            # 使用mb_substr函数截断字符串，并加上省略号
            $string = mb_substr($string, 0, $length, 'UTF-8') . $ellipsis;
        }
        # 返回截断后的字符串
        return $string;
    }



    /**
     * @param $data
     * @return void
     * 回调，不同的应用需要有不同的回调地址
     */
    public static function subscribeCallback($data)
    {
        $encodingAesKey = config('enterprise_wechat.encodingAesKey'); //回调里面的EncodingAESKey
        $token = config('enterprise_wechat.token'); //回调里面的token
        $corpId = config('enterprise_wechat.corpId'); //企业id

        $sVerifyMsgSig = $data['msg_signature'];
        $sVerifyTimeStamp = $data['timestamp'];
        $sVerifyNonce = $data['nonce'];
        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $corpId);


        $xmldata = file_get_contents("php://input");
        $sEchoStr = '';
        $errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $xmldata, $sEchoStr);
        $data = simplexml_load_string($sEchoStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = json_encode($data);
        $data = json_decode($data, true);
        return $data;


    }
}
